package com.zihan.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 本案例对应4.1.6 实现服务端与客户端多次的往来通信
 * 评价：不是自动的检测消息与回复，故没有写完
 * Created by dwlijx on 2021/5/3.
 * connect to lijx@zjhcsoft.com
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8088);
        Socket socket = serverSocket.accept();
        //输入开始
        InputStream inputStream = socket.getInputStream();
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        int length = objectInputStream.readInt();//获取长度
        byte[] byteArray = new byte[length];
        objectInputStream.readFully(byteArray);
        String newString = new String(byteArray);
        System.out.println(newString);
        //输入结束

        //输出开始
        OutputStream outputStream = socket.getOutputStream();
        String strA = "客户端你好A\n";
        String strB = "客户端你好B\n";
        String strC = "客户端你好C\n";
        int allStrLen = (strA + strB + strC).getBytes().length;
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeInt(allStrLen);
        objectOutputStream.flush();//第一次写入
        objectOutputStream.write(strA.getBytes());
        objectOutputStream.write(strB.getBytes());
        objectOutputStream.write(strC.getBytes());
        objectOutputStream.flush();//第二次写入
        //输出结束



    }
}
